import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/user.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/cache.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/localstorage.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/modal_util/index.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class SettingIndexPage extends StatefulWidget {
  const SettingIndexPage({super.key});

  @override
  State<SettingIndexPage> createState() => _SettingIndexPageState();
}

class _SettingIndexPageState extends State<SettingIndexPage> {
  String? totalCache;

  @override
  void initState() {
    super.initState();
    getCacheSize();
  }

  /// 关于我们
  Future aboutUsHandle() async {
    ModalUtil.showBlurGeneralDialogWidget(
        context: context,
        modalWidget: Center(
          child: Container(
            width: 500.w,
            height: 660.w,
            padding: EdgeInsets.only(top: 70.w, bottom: 48.w, left: 65.w, right: 65.w),
            decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                CommonText(txt: Characters('——旨在为用户打造一个学习交流的平台。我们将以“传承传统文化精髓、解读华夏智慧精华、传播中国传统文明”为己任，热享出彩，为国学文化的发展传承做出一份努力。').join('\u{2006}'), letterSpacing: -1, height: 1.6),
                CommonBtnWidget(txt: '返回', size: Size(330.w, 80.w), onTap: () {context.pop();}),
              ],
            ),
          ),
        )
    );
  }

  /// 退出登录
  Future exitHandle() async {
    ModalUtil.showBlurGeneralDialogWidget(
      context: context,
      modalWidget: Center(
        child: Container(
          width: 500.w,
          height: 300.w,
          padding: EdgeInsets.only(top: 70.w, bottom: 48.w),
          decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(60.w))
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const CommonText(txt: '确定退出当前账号吗？', weight: FontWeight.bold),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CommonBtnWidget(txt: '返回', size: Size(160.w, 80.w), fontSize: 30.sp, onTap: () {context.pop();}),
                  SizedBox(width: 10.w),
                  CommonBtnWidget(txt: '确定', active: false, size: Size(160.w, 80.w), fontSize: 30.sp, onTap: () async {
                    context.read<UserProvider>().clearStore();
                    final pref = await LocalStorage.getInstance();
                    pref.clear();
                    if (mounted) {
                      context.pop();
                      context.go('/');
                    }
                  })
                ],
              )
            ],
          ),
        ),
      )
    );
  }
  /// 获取缓存大小
  Future getCacheSize() async {
    final size = await CacheUtil.total();
    setState(() {
      totalCache = size;
    });
  }
  /// 清空缓存
  Future clearCache() async{
    if (totalCache == '0' || totalCache == null || totalCache == '') {
      EasyLoading.showSuccess('缓存已清理');
      return;
    }
    EasyLoading.show(status: '正在清理缓存...');
    await CacheUtil.clear();
    EasyLoading.dismiss();
    EasyLoading.showSuccess('缓存已清理');
    setState(() {
      totalCache = null;
    });
  }

  /// 注销用户
  Future deleteUserModal() async {
    ModalUtil.showBlurGeneralDialogWidget(
        context: context,
        modalWidget: Center(
          child: Container(
            width: 500.w,
            height: 660.w,
            padding: EdgeInsets.only(top: 70.w, bottom: 48.w, left: 65.w, right: 65.w),
            decoration: BoxDecoration(
                color: ColorStyle.themeLightColor,
                border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                CommonText(txt: Characters('该账号下的全部个人资料、堪舆记录、消费记录及会员服务数据将会被彻底删除且无法找回。').join('\u{2006}'), letterSpacing: -1, height: 1.6),
                const CommonText(txt: '确定要注销当前账号吗？', weight: FontWeight.bold),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CommonBtnWidget(txt: '返回', size: Size(160.w, 80.w), onTap: () {context.pop();}),
                    SizedBox(width: 10.w),
                    CommonBtnWidget(txt: '确定', active: false, size: Size(160.w, 80.w), onTap: deleteUserHandle)
                  ],
                )
              ],
            ),
          ),
        )
    );
  }

  Future deleteUserHandle() async {
    final userProvider = context.read<UserProvider>();
    final result = await UserAPI.deleteUser(context);
    if (result) {
      userProvider.clearStore();
      final pref = await LocalStorage.getInstance();
      pref.clear();
      if (mounted) {
        context.pop();
        context.go('/');
      }
    }
  }

  Widget itemBuilder({
    required String iconUrl,
    required String txt,
    required GestureTapCallback onTap,
    bool showBorder = true,
    Widget? action
  }) {
    return Material(
      color: ColorStyle.themeLightColor,
      child: InkWell(
        onTap: onTap,
        child: Container(
          height: 100.w,
          padding: EdgeInsets.only(bottom: 15.w),
          alignment: Alignment.bottomLeft,
          decoration: BoxDecoration(
            border: showBorder ? Border(
              bottom: BorderSide(width: 2.w, color: ColorStyle.borderColor)
            ) : null
          ),
          child: Row(
            children: [
              Image.asset(iconUrl, width: 40.w),
              SizedBox(width: 5.w),
              Expanded(child: CommonText(txt: txt)),
              if (action == null)
                Image.asset('assets/icons/icon_arrow_right.png', width: 10.w)
              else
                action
            ],
          ),
        ),
      ),
    );
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context, showActions: false),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: Padding(
        padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, Constant.PAGEPADDING.w),
        child: Column(
          children: [
            const CommonTitleWidget(txt: '设置'),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 40.w, vertical: 5.w),
              margin: EdgeInsets.only(top: 20.w, bottom: 120.w),
              decoration: BoxDecoration(
                color: ColorStyle.themeLightColor,
                border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                borderRadius: BorderRadius.all(Radius.circular(60.w))
              ),
              child: Column(
                children: [
                  itemBuilder(
                    iconUrl: 'assets/icons/icon_setting_edit.png',
                    txt: '编辑资料',
                    onTap: () {
                      context.push('/setting_edit_user_info');
                    }
                  ),
                  // itemBuilder(
                  //   iconUrl: 'assets/icons/icon_setting_account.png',
                  //   txt: '账号与安全',
                  //   onTap: () {
                  //     context.push('/setting_account_safe');
                  //   }
                  // ),
                  // itemBuilder(
                  //   iconUrl: 'assets/icons/icon_setting_feedback.png',
                  //   txt: '意见与反馈',
                  //   onTap: () {
                  //     context.push('/setting_feedback');
                  //   }
                  // ),
                  itemBuilder(
                    iconUrl: 'assets/icons/icon_setting_version.png',
                    txt: '软件版本',
                    action: const CommonText(txt: 'v1.0.0'),
                    onTap: () {}
                  ),
                  itemBuilder(
                    iconUrl: 'assets/icons/icon_setting_clear.png',
                    txt: '清理缓存',
                    action: CommonText(txt: totalCache ?? '0KB'),
                    onTap: clearCache
                  ),
                  itemBuilder(
                    iconUrl: 'assets/icons/icon_setting_exit.png',
                    txt: '退出登录',
                    onTap: exitHandle
                  ),
                  itemBuilder(
                    iconUrl: 'assets/icons/icon_setting_logout.png',
                    txt: '注销账户',
                    onTap: deleteUserModal
                  ),
                  itemBuilder(
                    iconUrl: 'assets/icons/icon_setting_about.png',
                    txt: '关于我们',
                    showBorder: false,
                    onTap: aboutUsHandle
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
